package server;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;

public class UDPServer {
	/**
	 * @param args
	 * @throws SocketException 
	 */

	public static void main(String[] args) throws IOException {
		String request;							// Message received by the server.
		String reply = "PONG";					// Message the server will send back to the client.
		String myhello = "My address";			// Message sent when when the server announces himself on Multicast.
		final String multicastAddress = "225.12.10.71";	// Address of Multicast channel.
		byte[] msgOut = (reply).getBytes();		// Message to send in the packet.
		final byte[] hello = (myhello).getBytes();		// Message to send in the announcer packet.
		final int serverPort = 5555;			// Server port.
		final int multicastPort = 1971;			// Port of Multicast channel.
		
		// Waiting for a request.
		final DatagramSocket s = new DatagramSocket(serverPort);
		byte[] msg = new byte[256];
		DatagramPacket p = new DatagramPacket(msg, 256);
		System.out.println("Server online...\n");
		
		// Create a thread to announce server on Multicast channel.
		(new Thread() {
			public void run() {
				InetAddress multicastChannel = null;
				try {
					multicastChannel = InetAddress.getByName(multicastAddress);
				} catch (UnknownHostException e1) {
					e1.printStackTrace();
				}
				DatagramPacket announcer = new DatagramPacket(hello, hello.length, multicastChannel, multicastPort);
				for(;;) {
					try {
						System.out.println("Announcing my address.\n");
						s.send(announcer);
					} catch (IOException e1) {
						e1.printStackTrace();
					}
	        		try {
	        			System.out.println("Sleeping for 1000 ms.\n");
						sleep(1000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		}).start();
		
		// Receive requests.
		s.receive(p);
		request = new String(p.getData(), 0, p.getLength());
		System.out.println("Request received: " + request + "\n");

		// Replying to a request.
		DatagramPacket pr = new DatagramPacket(msgOut, msgOut.length, p.getAddress(), p.getPort());
		s.send(pr);
		System.out.println("Reply sent: " + reply + "\n");			
	}
}
